<?php
/**
 * 描述
 * Created by Paco
 * Date: 2018/10/19 Time: 10:08
 */

namespace App\Lib\Utils;


use App\Models\Order\Order;
use App\Traits\ApiRespond;
use ReflectionClass;

class OrderFilter
{
    use ApiRespond;

    public function setPrice($order, $rule)
    {
        $coupon = new ReflectionClass('app\Lib\Utils\Coupon');
        $obj = $coupon->newInstance();

        //基本价格
        $price = $rule->basic_price;

        //有房
        if ($order->house_type > 0) {
            $price += $rule->house_price;
        }

        //有车
        if ($order->had_car > 0) {
            $price += $rule->car_price;
        }

        //有商业保险
        if ($order->had_insurance > 0) {
            $price += $rule->insurance_price;
        }

        //有社保
        if ($order->had_social_security > 0) {
            $price = $rule->social_security_price;
        }

        return $price;
    }


    public function setOrdersPrice($order_numbers = [], $rule_id = 0, $all = false)
    {

        $rule = $this->getRules($rule_id);
        if (!$rule) {
            return $this->throwRespondError(10603);
        }

        if ($order_numbers) {
            $orders = Order::query()->whereIn('order_number', $order_numbers)->get();
        } else {
            if (!$all) {
                $orders = Order::query()->where('is_hand_set', 0)
                    ->where('is_saled', 0)->get();
            } else {
                $orders = Order::query()->where('is_saled', 0)->get();
            }
        }

        if (!$orders) {
            return $this->throwRespondError(10109);
        }

        try {
            foreach ($orders as $item) {
                $item->price = $this->setPrice($item, $rule);
                $item->save();
            }
        } catch (\Exception $e) {
            $this->throwRespondError(10604);
        }
    }

    public function getRules($rule_id)
    {
        if ($rule_id) {
            $rule = Rule::query()->find($rule_id);
        } else {
            $rule = Rule::query()->where('default', 1)->first();
        }

        return $rule;
    }
}